package handlers

import (
	"GIN-API/internal/models"
	"GIN-API/internal/service"
	"github.com/gin-gonic/gin"
	"net/http"
)

// UserHandler 定义用户控制器层结构体
type UserHandler struct {
	userService *service.UserService
}

// NewUserHandler 创建用户控制器层实例
func NewUserHandler(userService *service.UserService) *UserHandler {
	return &UserHandler{
		userService: userService,
	}
}

// GetUserByUsername 获取用户信息
func (uh *UserHandler) GetUserByUsername(c *gin.Context) {
	username, _ := c.Get("username")
	user, err := uh.userService.GetUserByUsername(username.(string))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户信息失败"})
		return
	}
	if user == nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
		return
	}
	c.JSON(http.StatusOK, user)
}

// UpdateUser 更新用户信息
func (uh *UserHandler) UpdateUser(c *gin.Context) {
	username, _ := c.Get("username")
	var updatedUser models.User
	if err := c.ShouldBindJSON(&updatedUser); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
		return
	}
	user, err := uh.userService.GetUserByUsername(username.(string))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户信息失败"})
		return
	}
	if user == nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
		return
	}
	// 更新用户信息
	user.Username = updatedUser.Username
	user.Password = updatedUser.Password
	user.Role = updatedUser.Role

	if err := uh.userService.UpdateUser(user); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新用户信息失败"})
		return
	}
	c.JSON(http.StatusOK, user)
}

// DeleteUser 删除用户
func (uh *UserHandler) DeleteUser(c *gin.Context) {
	username, _ := c.Get("username")
	user, err := uh.userService.GetUserByUsername(username.(string))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户信息失败"})
		return
	}
	if user == nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
		return
	}
	if err := uh.userService.DeleteUser(user.ID).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "删除用户失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "用户删除成功"})
}
